<template>
    <div class="pl-26px text-14px text-#999">完整填写文章基本信息，是关键词推广的基本前提</div>
    <div class="pl-26px pt-26px">
        <el-form ref="ruleFormRef" :model="props.ruleForm" :rules="rules" label-width="124px">
            <el-form-item label="文章标题" prop="name">
                <div class="w-400px">
                    <el-input ref="nameRef" v-model="props.ruleForm.name" placeholder="请输入文章标题" />
                </div>
            </el-form-item>
            <el-form-item label="所在地区" prop="area">
                <ProvinceCitySelector ref="provinceCitySelector" v-model:province="props.ruleForm.province"
                    v-model:city="props.ruleForm.city" />
            </el-form-item>
            <el-form-item label="详细介绍" prop="content">
                <div class="w-90%">
                    <vue-ueditor-wrap v-model="props.ruleForm.content" editor-id="editor1" :config="editorConfig"
                        :editorDependencies="['ueditor.config.js', 'ueditor.all.js']" />
                </div>
                <div class="text-12px text-#999">为了保证关键词名效果，详细介绍请不低于200个汉字，在详细内容中不要填写任何联系方式(如联系人、联系电话、传真、手机、邮箱、网站等。 </div>
            </el-form-item>
            <el-form-item label="文章来源" prop="source">
                <div class="w-400px">
                    <el-input ref="nameSource" v-model="props.ruleForm.source" placeholder="请输入文章来源" />
                </div>
            </el-form-item>
            <el-form-item>
                <div class="pb-40px">
                    <el-button :loading="loading" type="primary" @click="handleNext(ruleFormRef)">下一步</el-button>
                </div>
            </el-form-item>

        </el-form>
    </div>
</template>

<script setup lang="ts">
import ProvinceCitySelector from '@/components/ProvinceCitySelector/index.vue'
import { checkArticleContentApi,checkNameContent,sensitiveWordsCheckApi } from '@/api/b2b/index'
import { normalStr, violationStr } from '@/utils/checkStr'
import { findMatchingElements, highlightMatches, debounce } from '@/utils/index'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { CircleCloseFilled } from '@element-plus/icons-vue'

const props = defineProps<{
    modelValue: number
    ruleForm: any
}>()

// 使用 computed + watch 实现双向绑定效果
const step = ref(props.modelValue)

watch(
    () => props.modelValue,
    (newVal) => {
        if (typeof newVal === 'number') {
            step.value = newVal
        }
    }
)

const emit = defineEmits(['update:modelValue', 'step-1-complete'])

const ruleFormRef = ref()
const nameRef = ref()
const isError = ref(false)
const loading = ref(false)

const rules = reactive({
    name: [
        { min: 3, max: 35, required: true, message: '请输入文章标题', trigger: 'blur', validator: checkName }
    ],
    content: [
        { required: true, validator: checkContent }
    ],
})

const provinceCitySelector = ref<InstanceType<typeof ProvinceCitySelector> & ProvinceCitySelectorInstance | null>(null)

const editorConfig = {
    // 后端服务地址，后端处理参考
    // https://open-doc.modstart.com/ueditor-plus/backend.html
    serverUrl: import.meta.env.VITE_APP_EDITOR_URL, 
    UEDITOR_HOME_URL: '/static/UEditorPlus/',
    UEDITOR_CORS_URL: '/static/UEditorPlus/',
    /* 上传图片配置项 */
    imageActionName: 'uploadFile' /* 执行上传图片的action名称 */,
    imageFieldName: 'file' /* 提交的图片表单名称 */,
    imageMaxSize: 2048000 /* 上传大小限制，单位B */,
    imageAllowFiles: ['.png', '.jpg', '.jpeg', '.gif', '.bmp'] /* 上传图片格式显示 */,
    imageCompressEnable: true /* 是否压缩图片,默认是true */,
    imageCompressBorder: 1600 /* 图片压缩最长边限制 */,
    imageInsertAlign: 'none' /* 插入的图片浮动方式 */,
    imageUrlPrefix: '' /* 图片访问路径前缀 */,
    imagePathFormat: '' /* 上传保存路径,可以自定义保存路径和文件名格式 */,
    autoHeightEnabled:false,

    serverHeaders: {
        'Authorization': sessionStorage.getItem('X-token')
    },
}

async function handleNext(formEl: any) {
    loading.value = true
    if (!formEl) return
    await formEl.validate(async (valid:boolean, fields:any) => {
        if (valid) {
            const newStep = step.value + 1
            step.value = newStep

            if (provinceCitySelector.value) {
                props.ruleForm.province = provinceCitySelector.value.selectedProvince?.name
                props.ruleForm.city = provinceCitySelector.value.selectedCity
            }
            // //检测输入内容
            try {
                const res:ResType = await checkNameContent({
                    txt: props.ruleForm.name,
                    content: props.ruleForm.content
                })
                if(res.code === 200){
                    loading.value = false
                    emit('update:modelValue', step.value)
                    emit('step-1-complete', props.ruleForm)
                }
            } catch (error: any) {
                if (error.response && error.response.status === 405){
                    markError(props.ruleForm.content,error.response.data.message)
                    confirmMessageBox(CircleCloseFilled, `您发布的信息中含有虚假宣传、违禁词等敏感词，或含有本平台规定不得发布的医疗器械、 诊断试剂、药品等相关内容：(如：${error.response.data.message})，请检查修改后提交。`,)
                    loading.value = false
                    return false
                }
            }   
        } else {
            console.log('error submit!', fields)
        }
    })
}

function checkName(rule: any, value: any, callback: any) {
    if(value === ''){
        loading.value = false
        callback(new Error('请输入文章标题'))
    }else{
        const arr = findMatchingElements(value, normalStr)
        if (arr.length) {
            confirmMessageBox(CircleCloseFilled, '文章标题里不能包含 ' + arr[0] + ' 请修改', '','',() => {
                nameRef.value.focus()
            })
            callback(new Error()) // 必须调用 callback 来通知校验失败
        } else {
            callback() // 校验通过
        }
    } 
}

function checkContent(rule: any, value: any, callback: any) {
    if(value === ''){
        loading.value = false
        callback(new Error('请输入文章详细内容'))
    }else{
        value = value.replace(/<[^>]+>/g, '')
        if(value.length < 200){
            confirmMessageBox(CircleCloseFilled, '文章详细内容不能少于 200 个字符', '确定','',() => {
                loading.value = false
            },() => {
                loading.value = false
            })
            callback(new Error('文章详细内容不能少于 200 个字符'))
        }
        const arr = findMatchingElements(value, violationStr)
        if (arr.length) {
            const highlightedContent = highlightMatches(value, arr)
            props.ruleForm.content = highlightedContent;
            confirmMessageBox(CircleCloseFilled, '您发布的信息中不能包含 ' + arr[0] + ' 请检查修改后提交','','',() => {
                loading.value = false
            },() => {
                loading.value = false
            })
            callback(new Error())
        } else {
            callback() // 校验通过
        }
    }
}

// 提取 debounced 函数，并在 watch 中复用它
const debouncedCheckContent = debounce(async (newContent: string) => {
    if (!isError.value) {
        try{
            const res:ResType = await checkArticleContentApi({ content: newContent })
            if(res.code === 200){
                return true
            }
        }catch(error:any){
            confirmMessageBox(CircleCloseFilled, error.response.data.message, '确定','',() => {
                loading.value = false
                isError.value = false
            })
            return false
        }
    }
}, 500);

function markError(content:string,word:string){
    const sensitiveWords = word.split('|')
    const highlightedContent = highlightMatches(content, sensitiveWords)
    props.ruleForm.content = highlightedContent;
}

// watch(
//     () => props.ruleForm.content,
//     (newContent) => {
//         if(newContent){
//             debouncedCheckContent(newContent)
//         }
//     }
// );

onMounted(() => {
    //给地区选择器赋值
    if (provinceCitySelector.value) {
        const selector = provinceCitySelector.value
        selector.selectedProvince.name = props.ruleForm.province
        selector.selectedCity = props.ruleForm.city
    }
})
</script>

<style scoped></style>